﻿using System;
using System.Text;

namespace Bpms.Cache
{
    /// <summary>
    /// 缓存操作入口
    /// </summary>
    public class CacheContext
    {
        private static ICacheStrategy cs;
        private static object lockHelper = new object();
        private static volatile CacheContext instance = null;

        private CacheContext(ICacheStrategy cs)
        {
            //
            LoadCache(cs);
            cs.Accept(new CacheLogAdapter());
        }

        static CacheContext()
        {

        }

        public void LoadCache(ICacheStrategy ics)
        {
            lock (lockHelper)
            {
                cs = ics;
            }
        }


        /// <summary>
        /// 单体模式返回当前类的实例
        /// </summary>
        /// <returns></returns>
        public static CacheContext GetCacheService(ICacheStrategy cs)
        {
            if (instance == null)
            {
                lock (lockHelper)
                {
                    if (instance == null)
                    {
                        instance = new CacheContext(cs);
                    }
                }
            }

            return instance;
        }

        public virtual void AddObject(string objectId, object objectValue)
        {
            //当缓存到期时间为0或负值,则不再放入缓存
            if (cs.TimeOut <= 0)
            {
                return;
            }
            cs.AddObject(objectId, objectValue);
        }

        public virtual void AddObject(string objectId, object objectValue, string[] files)
        {
            //当缓存到期时间为0或负值,则不再放入缓存
            if (cs.TimeOut <= 0)
            {
                return;
            }
            cs.AddObjectWithFileChange(objectId, objectValue, files);
        }

        public virtual object RetrieveObject(string objectId)
        {
            return cs.RetrieveObject(objectId);
        }

        public virtual void RemoveObject(string objectId)
        {
            lock (lockHelper)
            {
                cs.RemoveObject(objectId);
            }
        }
    }
}
